package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
	
	@Autowired
	private AddressBookMapper addressBookMapper;
	
	/**
	 * 新增地址
	 *
	 * @param addressBook
	 */
	@Override
	public void addAddress(AddressBook addressBook) {
		addressBook.setUserId(BaseContext.getCurrentId());
		addressBook.setIsDefault(0);
		addressBookMapper.addAddress(addressBook);
	}
	
	/**
	 * 获取地址
	 *
	 * @return
	 */
	@Override
	public List<AddressBook> getAddress() {
		AddressBook addressBook = AddressBook.builder().userId(BaseContext.getCurrentId()).build();
		return addressBookMapper.getAddress(addressBook);
	}
	
	/**
	 * 获取默认地址
	 *
	 * @return
	 */
	@Override
	public AddressBook getDefault() {
		AddressBook addressBook = AddressBook.builder().userId(BaseContext.getCurrentId()).isDefault(1).build();
		return addressBookMapper.getDefault(addressBook);
	}
	
	/**
	 * 根据id获取地址
	 *
	 * @param id
	 * @return
	 */
	@Override
	public AddressBook getAddressById(Long id) {
		AddressBook addressBook = AddressBook.builder().id(id).build();
		return addressBookMapper.getAddress(addressBook).get(0);
	}
	
	/**
	 * 根据id修改地址
	 *
	 * @param addressBook
	 */
	@Override
	public void updateAddress(AddressBook addressBook) {
		addressBookMapper.putAddress(addressBook);
	}
	
	/**
	 * 修改默认地址
	 *
	 * @param addressBook
	 */
	@Override
	public void putDefault(AddressBook addressBook) {
		AddressBook aDefault = getDefault();
		if (aDefault != null) {
			aDefault.setIsDefault(0);
			addressBookMapper.putAddress(aDefault);
		}
		addressBook.setIsDefault(1);
		addressBookMapper.putAddress(addressBook);
	}
	
	/**
	 * 删除地址
	 *
	 * @param id
	 */
	@Override
	public void deleteAddress(Long id) {
		addressBookMapper.deleteAddress(id);
	}
}
